import Vue from "vue";
import VueRouter from "vue-router";
import store from "../store/index.js";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { System7, System1 } from "@/api";
import { getToken } from "../utils/auth.js";
import { MessageBox, Message } from "element-ui";
NProgress.configure({ showSpinner: false });
Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: { name: "Home" }
  },
  {
    path: "/Home",
    component: () => import("../layout"),
    children: [
      {
        path: "/Home",
        name: "Home",
        component: () => import("../view/Home")
      }
    ]
  },
  {
    path: "/Login",
    name: "Login",
    component: () => import("../view/Login")
  }
];

const createRouter = () =>
  new VueRouter({
    mode: "hash",
    base: process.env.BASE_URL,
    routes
  });
const router = createRouter();
router.beforeEach(async (to, from, next) => {
  NProgress.start();
  if (to.path === "/Login") {
    next();
    NProgress.done();
  } else if (hasLogin()) {
    const hasRoles =
      store.getters["Router/MenuData"] &&
      store.getters["Router/MenuData"].length > 0;
    //如果有菜单了
    if (hasRoles) {
      //如果菜单有标识 获取按钮权限
      if (to.meta && to.meta.activeMenu) {
        //记录按钮权限
        const btns = await System1.getBtnPermission(to.meta.activeMenu);
        store.dispatch("User/setBtnPermission", btns);
      }
      //正常打开页面
      next();
    } else {
      //获取数据
      const menuData = await System7.get();
      if (menuData.length != 0) {
        store.dispatch("Router/setMenuData", menuData).then(() => {
          next({ ...to, replace: true });
        });
      } else {
        Message({
          message: "网络错误",
          type: "error",
          duration: 5 * 1000
        });
        next({ path: "/Login" });
      }
    }
  } else {
    next({ path: "/Login" });
  }
});
router.afterEach(() => {
  //记录页面打开日志
  System1.ClickMenuLog();
  NProgress.done(); // 结束Progress
});
//是否登录
const hasLogin = () => {
  return !!getToken();
};
export function resetRouter() {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher; // reset router
}
export default router;
